from json import dumps


import requests

from common.LoggerUtil import log


class RequestsUtil:
    """封装请求类"""

    def get(self, url, params=None, **kw):
        """
      get请求封装
        """
        try:
            resp = requests.get(url, params=params, **kw)
            self.api_log('GET', url,  code=resp.status_code)
        except Exception as e:
            # 记录日志信息
            log.error("接口请求异常,原因：{}".format(e))
            raise e
        else:
            return resp

    def post(self, url, data=None, json=None, **kw):
        """
        post请求封装

        """
        try:
            resp = requests.post(url, data=data, json=json, verify=False,**kw)
            self.api_log('POST', url, json=json,
                         code=resp.status_code,)
        except Exception as e:
            log.error("接口请求异常,原因：{}".format(e))
            raise e

        else:
            return resp

    def visit(self, method, url, params=None, data=None, json=None, **kw):
        """访问接口"""
        if method.lower() == 'get':
            return self.get(url, params=params, **kw)

        elif method.lower() == 'post':

            return self.post(url, data=data, json=json, params=params, **kw)

    def json(self, method, url, params=None, data=None, json=None, **kw):
        """获取json数据"""
        resp = self.visit(method, url, params=params, data=data, json=json, **kw)


        # 获取json格式响应结果
        try:

            return resp.json()
        except:
            # 记录日志
            log.error(f"{resp}--不是json个格式数据")

    def api_log(self,method, url, headers=None, params=None, json=None, cookies=None, file=None, code=None,
                res_text=None,
                res_header=None):
        log.info("请求方式====>{}".format(method))
        log.info("请求地址====>{}".format(url))
        log.info("请求体====>{}".format(dumps(json, indent=4)))
        log.info("接口响应状态码====>{}".format(code))
        # log.info("接口响应体为====>{}".format(res_text.decode("unicode_escape")))


class RequestsCookieUtil:
    """带cookie的请求模式"""

    def __init__(self):
        # 使用session会话模式
        self.session = requests.Session()

    def get(self, url, params=None, **kw):
        try:
            resp = self.session.get(url, params=params, **kw)
        except Exception as e:
            # 记录日志信息
            log.error(f"{url}--该get请求访问失败")
        else:
            return resp

    def post(self, url, data=None, json=None, **kw):
        try:

            resp = self.session.post(url, data=data, json=json, **kw)
        except Exception as e:
            # 记录日志信息
            log.error(f"{url}--该post请求访问失败")
        else:
            return resp

    def visit(self, method, url, params=None, data=None, json=None, **kw):
        """访问接口"""
        if method.lower() == 'get':
            return self.get(url, params=params, **kw)
        elif method.lower() == 'post':
            return self.post(url, data=data, json=json, params=params, **kw)
        else:
            # requests通用方式
            return requests.request(method, url, data=data, json=json, params=params, **kw)

    def json(self, method, url, params=None, data=None, json=None, **kw):
        """获取json数据"""

        resp = self.visit(method, url, params=params, data=data, json=json, **kw)
        # 获取json数据
        try:
            return resp.json()
        except:
            # 记录日志
            log.error(f"{resp}--不是json个格式数据")


if __name__ == '__main__':
    # Demo调试
    r = RequestsUtil()
    ID = "wwd8cd7f5fb2f3e477"
    SECRET = "XqF5d_TeAMVBc6b90S_Xhv0Do029daOV3GIUBaX1Z-0"

    res = r.json('get', 'https://qyapi.weixin.qq.com/cgi-bin/gettoken1',
                 params={"corpid": ID, "corpsecret": SECRET})
    print(res)
